<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增借货订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //此角色的最大折扣权限。        
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '100%'
        });
        
        //所有客户
        var customerTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:70px">{number}</div><div style="float:left;width:230px">|{name}</div>| {phone}', '</div></tpl>');
        var customerStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/customer/getAllCustomers?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number',
              convert:function(value,record){
                if (value === ""){
                  return "未设置编号"
                }else{
                  return value;
                }
              }
            }, {
              name: 'name'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'address'
            }])
        });
        
        var toCustomer = new Ext.form.ComboBox({
          store: customerStore,
          fieldLabel: '到客户',
          allowBlank: false,
          blankText: "客户必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'customer_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: customerTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:"all",
          selectOnFocus:true
        });

        toCustomer.on('select', function(combo, record, index) {
          if (record.get('linkman') === "" ){
            linkman.setValue(record.get('name'));
          }else{
            linkman.setValue(record.get('linkman'));
          }
          phone.setValue(record.get('phone'));
          deliveryAddress.setValue(record.get('address'));
        });

        var addCustomerButton = new Ext.Button({
          text: '添加客户',
          iconCls: 'addItem',
          scale: 'small',
          handler: onAddCustomerButtonClick
        });

        function onAddCustomerButtonClick(){
          newCustomerWin = new Ext.Window({
            layout: 'fit',
            width:618,
            height:300,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            //modal: true,
            title: '添加客户',
            autoLoad: {
              url: "/customer/newCustomer",
              scripts: true
            }
          });
          newCustomerWin.resizable = false;
          newCustomerWin.show();
        }
        
        //要求发货时间
        var actionDate = new Ext.form.DateField({
          fieldLabel: '发货日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "发货日期必须选择",
          emptyText: '发货日期...',
          anchor: '95%'
        });
        
        //合同号
        var contractNumber = new Ext.form.TextField({
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = new Ext.form.TextField({
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false,
          anchor: '95%'
        });
        
        //联系电话
        var phone = new Ext.form.TextField({
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false,
          anchor: '95%'
        });

        var deliveryAddress = new Ext.form.TextField({
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '100%'
        });

        //销售员
        var salesTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:35px">{number}</div><div style="float:left;width:55px">|{name}</div>', '</div></tpl>');
        var salesStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/employee/getAllEmployees?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });

        var sales = new Ext.form.ComboBox({
          store: salesStore,
          fieldLabel: '销售员',
          allowBlank: false,
          blankText: "销售员必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'sales_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: salesTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          anchor: '95%',
          //editable:false,
          triggerAction: 'all',
          selectOnFocus:true
        });
        
        //--------------------------------------------------------------------------        
        
        var productTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item"><div style="float:left; width:230px">{name}</div><div>', '{is_suit}', '</div></div></tpl>');
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product/getAllProducts?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //供应商产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '供应商产品',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          displayField: 'name',
          anchor: '90%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          
          var loanItemRecord = loanDetailSM.getSelected();
          if (!loanItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(loanDetailDS,record.get('id'),loanItemRecord.id)){
            //删除当前记录
            loanDetailDS.remove(loanItemRecord);
          }else{
            if (loanItemRecord.get('product_id') != record.get('id')){
              loanItemRecord.set('number',record.get('number'));
              loanItemRecord.set('spec',record.get('spec'));
              loanItemRecord.set('unit',record.get('unit'));
              loanItemRecord.set('quantity',1);
              loanItemRecord.set('product_id',record.get('id'));
              //判断套装
              loanItemRecord.set('is_suit',record.get('is_suit'));
            }
          }
        });

        //借货订单列表Grid Store
        var loanDetailDS = new Ext.data.Store({
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'description'
            }, {
              name: 'quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //生成产品Grid的CM
        var loanDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        //var loanDetailSM = new Ext.grid.RowSelectionModel({singleSelect:true});
        var loanDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),loanDetailSM,{
              header: '产品名称',
              dataIndex: 'product_name',
              editor: productCBB,
              width: 290
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 100
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 40
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              width: 50
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 240,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '100%'
              })
            }
          ]});

        //生成要订单的产品的Grid
        var loanDetailGrid = new Ext.grid.EditorGridPanel({
          store: loanDetailDS,
          cm: loanDetailCM,
          sm: loanDetailSM,
          width: 950,
          height: 290,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = loanDetailGrid.getStore().recordType;
                var record = new Product({
                  product_name: '请选择产品'
                });
                loanDetailGrid.stopEditing();
                loanDetailDS.insert(0, record);
                loanDetailGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = loanDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                loanDetailDS.remove(record);
              }
            }]
        });
        
        //提交按钮
        var submitButton = new Ext.Button({
          text: '提交',
          tooltip: '保存并提交借货订单。',
          iconCls: 'icon-save',
          handler: function(){
            //.setDisabled(true);
            //如果输入了首付金额，就要填写付款方式

            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
              return;
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
              return;
            }
            
            if (loanFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = loanFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              
              Ext.Ajax.request({
                url : '/loan/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = new Ext.Button({
          text: '暂存',
          tooltip: '暂时保存借货订单。',
          iconCls: 'temp-save',
          handler: function(){
            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }
            
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (loanFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              //没有添加产品，则提示
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = loanFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/loan/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        
        //关闭按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newLoanWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var loanFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'new_loan',
          labelWidth: 55,
          width: '950',
          labelAlign: 'right',          
          frame : true,
          url: '/loan/create',
          method: 'GET',
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .6,
                  layout: 'form',
                  border: false,
                  items: [toCustomer]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [addCustomerButton]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [contractNumber]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [linkman]
                }, {
                  columnWidth: .4,
                  layout: 'form',
                  border: false,
                  items: [phone]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [sales]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [loanDetailGrid]
                }]
            },temporary],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        loanFormPanel.render('new_loan');

      })
    </script>
  </head>
  <body>
    <div id="new_loan"></div>
  </body>
</html>